package com.bazaaroid.mobile.android;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import com.bazaaroid.mobile.android.adapter.ActiveDiscountAdapter;
import com.bazaaroid.mobile.android.adapter.CategoryAdapter;
import com.bazaaroid.mobile.android.adapter.ProductsAdapter;
import com.bazaaroid.mobile.android.db.DbBazaaAdapter;
import com.bazaaroid.mobile.db.model.partner.*;
import com.bazaaroid.mobile.rest.model.partner.*;
import com.bazaaroid.mobile.android.helper.AdvancedSearchParser;
import com.bazaaroid.mobile.android.helper.BazaaroidApiClient;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Visibility;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class Tabs extends /*ListActivity,*/ MapActivity {
	
	private String TAG = "[Tabs]";
	
	private Context mContext = null;
	
	private LinearLayout ll = null;
	private RelativeLayout rl1 = null;
	private RelativeLayout rl2 = null; // Bazaaroid search header
	private RelativeLayout rl3 = null; // Minimalistic search header
	private ImageButton searchButton1 = null;
	private ImageButton searchButton2 = null;
	private Button advancedSearchButton = null;
	private ImageView iconButton = null;
	private ImageButton resultButton = null;
	private ImageButton mapButton = null;
	private EditText searchBox = null;
	
	// search related fields
	boolean mOffline = true;
	private ListView lv1;
	private String lv_arr[] = null;	
	private DbBazaaAdapter dbBazaaAdapter = null;
	private BazaaroidApiClient apiClient = null;
	private String mQuery = null;
	private String mAdvancedQuery = null;
	private ArrayList</*Product*/?> mSearchResult = null;
	private ProductsAdapter mProductsAdapter = null;
	private ActiveDiscountAdapter mActiveDiscountAdapter = null;
	private CategoryAdapter mCategoryAdapter = null;
	private Runnable viewResults = null;
	private Runnable viewCategories = null;
	private ArrayAdapter<CharSequence> categoryValueAdapter = null;
	
	private ProgressDialog mProgressDialog = null;	
	private ListView mListViewResults = null;
	private ListView mListViewCategories = null;
	private MapView mMapResults = null;
	private FrameLayout mMapContainer = null;
	private MapController mapController = null;
	
	// GPS
	private LocationManager locationManager = null;
	private LocationListener locationListener = null;
    boolean gpsEnabled = false;
	
	// Display
	private int displayWidth = 0;
	private int displayHeight = 0;
	
	@Override
    protected boolean isRouteDisplayed() {
        return false;
    }
	
	private OnClickListener mOnClickListener1 = new OnClickListener() {    
		public void onClick(View v) {      
			displayBazaaroidSearch(true);
			searchBox = (EditText)findViewById(R.id.search_header_edit_box);
			searchBox.requestFocus();
			searchBox.setSingleLine();
			searchBox.setOnKeyListener(mOnKeyListenerEnter);
		};
	};
	
	private OnClickListener mOnClickListener2 = new OnClickListener() {    
		public void onClick(View v) {      
			//displayBazaaroidSearch(false);
			
			/*displayBazaaroidSearch(true);
			
			ll.removeView(mListViewResults);
			ll.removeView(mMapResults);
			ll.addView(mListViewCategories);
			
			searchBox = (EditText)findViewById(R.id.search_header_edit_box);
			searchBox.requestFocus();
			searchBox.setSingleLine();
			searchBox.setOnKeyListener(mOnKeyListenerEnter);*/
			
			if(!rl2.isShown())
			{
			
				  // Switch search header
				if(rl3.isShown())
				{
					ll.removeView(rl3);
				  	ll.addView(rl2, 0);
				}
				  /*ll.removeView(rl3);
				  ll.addView(rl2, 0);*/
				  searchButton2 = (ImageButton)rl2.findViewById(R.id.search_header_button2);
				  advancedSearchButton = (Button)rl2.findViewById(R.id.search_header_advanced_search_text);
				  iconButton = (ImageView)rl2.findViewById(R.id.search_header_icon);		  
				  
				  searchBox = (EditText)rl2.findViewById(R.id.search_header_edit_box);
				  searchBox.requestFocus();
				  searchBox.setSingleLine();
				  searchBox.setOnKeyListener(mOnKeyListenerEnter);
	
				  searchButton2.setOnClickListener(mOnClickListenerSearch);
				  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
				  iconButton.setOnClickListener(mOnClickListener2);				
				
				// TODO: Treba dodati flagove kako bi se znalo koji je
				// view loadovan
				ll.removeView(mListViewResults);
				//ll.removeView(mMapResults);
				ll.removeView(mMapContainer);
				//ll.removeView(resultButton);
				ll.addView(mListViewCategories);
			displayCategories();
			}
		};
	};
	
	private OnClickListener mOnClickListenerSearch = new OnClickListener() {    
		public void onClick(View v) {     						
			displayResult(true);
			searchBox = (EditText)findViewById(R.id.search_header_edit_box);
			String query = searchBox.getText().toString();
			updateResultList(query, false);

			// Switch search header
			if(rl2.isShown())
			{
				ll.removeView(rl2);
			  	ll.addView(rl3, 0);
			}
			  //ll.removeView(rl2);
			  //ll.addView(rl3, 0);
			  searchButton2 = (ImageButton)rl3.findViewById(R.id.search_header_button2);
			  advancedSearchButton = (Button)rl3.findViewById(R.id.search_header_advanced_search_text);
			  iconButton = (ImageView)rl3.findViewById(R.id.search_header_icon);		  
			  
			  searchBox = (EditText)rl3.findViewById(R.id.search_header_edit_box);
			  searchBox.requestFocus();
			  searchBox.setSingleLine();
			  searchBox.setOnKeyListener(mOnKeyListenerEnter);

			  searchButton2.setOnClickListener(mOnClickListenerSearch);
			  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
			  iconButton.setOnClickListener(mOnClickListener2);				
		};
	};
	
	private OnClickListener mOnClickListenerAdvancedSearch = new OnClickListener() {    
		public void onClick(View v) {     
			displayResult(true);
			//TODO: display 'Advanced search' dialog-box
			//Button advSearchBtn = (Button)v;
			//advSearchBtn.setTextColor(Color.BLUE);
			
			  // Switch search header
			if(rl2.isShown())
			{
				ll.removeView(rl2);
			  	ll.addView(rl3, 0);
			}
			  //ll.removeView(rl2);
			  //ll.addView(rl3, 0);
			  searchButton2 = (ImageButton)rl3.findViewById(R.id.search_header_button2);
			  advancedSearchButton = (Button)rl3.findViewById(R.id.search_header_advanced_search_text);
			  iconButton = (ImageView)rl3.findViewById(R.id.search_header_icon);		  
			  
			  searchBox = (EditText)rl3.findViewById(R.id.search_header_edit_box);
			  searchBox.requestFocus();
			  searchBox.setSingleLine();
			  searchBox.setOnKeyListener(mOnKeyListenerEnter);

			  searchButton2.setOnClickListener(mOnClickListenerSearch);
			  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
			  iconButton.setOnClickListener(mOnClickListener2);				
			
			displayAdvancedSearchDialog();
			
			//advSearchBtn.setTextColor(Color.BLACK);
		};
	};
	
	private OnClickListener mOnClickListenerResult = new OnClickListener() {
		public void onClick(View v) {
			//ll.removeView(resultButton);
			//ll.addView(mapButton);
			displayResult(true);
		}
	};
	
	private OnClickListener mOnClickListenerMap = new OnClickListener() {
		public void onClick(View v) {
			//ll.removeView(mapButton);
			//ll.addView(resultButton);
			
			displayResult(false);
		}
	};
	
	private OnKeyListener mOnKeyListenerEnter = new OnKeyListener() {
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent keyEvent){
			if(keyCode == KeyEvent.KEYCODE_ENTER) // 'Enter' key
			{
						
				
				displayResult(true);
				searchBox = (EditText)findViewById(R.id.search_header_edit_box);
				String query = searchBox.getText().toString();
				searchBox.setText("");
				updateResultList(query, false);
				
				  // Switch search header
				if(rl2.isShown())
				{
					ll.removeView(rl2);
				  	ll.addView(rl3, 0);
				}
				  
				  searchButton2 = (ImageButton)rl3.findViewById(R.id.search_header_button2);
				  advancedSearchButton = (Button)rl3.findViewById(R.id.search_header_advanced_search_text);
				  iconButton = (ImageView)rl3.findViewById(R.id.search_header_icon);		  
				  
				  searchBox = (EditText)rl3.findViewById(R.id.search_header_edit_box);
				  searchBox.requestFocus();
				  searchBox.setSingleLine();
				  searchBox.setOnKeyListener(mOnKeyListenerEnter);

				  searchButton2.setOnClickListener(mOnClickListenerSearch);
				  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
				  iconButton.setOnClickListener(mOnClickListener2);							
				
				return true;
			}
			
			return false;
		}
	};
	
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	displayBazaaroidSearch(true);
			
			/*ll.removeView(mListViewResults);
			ll.removeView(mMapResults);
			ll.addView(mListViewCategories);
			
			searchBox = (EditText)findViewById(R.id.search_header_edit_box);
			searchBox.requestFocus();
			searchBox.setSingleLine();
			searchBox.setOnKeyListener(mOnKeyListenerEnter);*/

			  // Switch search header
	    	if(rl2.isShown())
	    	{
	    		moveTaskToBack(true);
	    	}
	    	else
	    	{
		    	if(rl3.isShown())
				{
					ll.removeView(rl3);
				  	ll.addView(rl2, 0);
				}
				  searchButton2 = (ImageButton)rl2.findViewById(R.id.search_header_button2);
				  advancedSearchButton = (Button)rl2.findViewById(R.id.search_header_advanced_search_text);
				  iconButton = (ImageView)rl2.findViewById(R.id.search_header_icon);		  
				  
				  searchBox = (EditText)rl2.findViewById(R.id.search_header_edit_box);
				  searchBox.requestFocus();
				  searchBox.setSingleLine();
				  searchBox.setOnKeyListener(mOnKeyListenerEnter);
	
				  searchButton2.setOnClickListener(mOnClickListenerSearch);
				  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
				  iconButton.setOnClickListener(mOnClickListener2);		    	
		    	
		    	ll.removeView(mListViewResults);
				//ll.removeView(mMapResults);
				ll.removeView(mMapContainer);
		    	//ll.removeView(resultButton);
				ll.addView(mListViewCategories);
				displayCategories();
	    	}
	    	
	        return true; 
	    } 
	    return super.onKeyDown(keyCode, event); 
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final Dialog dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		Button okButton = null;
	    switch (item.getItemId()) {
	        case R.id.menu_about:     
	        	//dialog = new Dialog(this);
	        	//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        	dialog.setContentView(R.layout.about);
	        	dialog.setCancelable(true);
	        	
	        	okButton = (Button)dialog.findViewById(R.id.about_ok_button);
	        	okButton.setWidth(displayWidth); 
	        	okButton.setOnClickListener(new OnClickListener(){
	        		@Override
	        		public void onClick(View v){
	        			dialog.dismiss();
	        		}
	        	});
	        	
	        	dialog.show();
	        	
	            break;
	        /*case R.id.menu_number_of_results:     
	        	//dialog = new Dialog(this);
	        	//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        	dialog.setContentView(R.layout.num_results);
	        	dialog.setCancelable(true);
	        	
	        	okButton = (Button)dialog.findViewById(R.id.num_results_ok_button);
	        	okButton.setWidth(displayWidth); 
	        	okButton.setOnClickListener(new OnClickListener(){
	        		@Override
	        		public void onClick(View v){
	        			dialog.dismiss();
	        		}
	        	});
	        	
	        	dialog.show();
	            break;
	        case R.id.menu_sync: 
	        	//dialog = new Dialog(this);
	        	//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        	dialog.setContentView(R.layout.syncronization);
	        	dialog.setCancelable(true);
	        	
	        	okButton = (Button)dialog.findViewById(R.id.sync_ok_button);
	        	okButton.setWidth(displayWidth); 
	        	okButton.setOnClickListener(new OnClickListener(){
	        		@Override
	        		public void onClick(View v){
	        			dialog.dismiss();
	        		}
	        	});
	        	
	        	dialog.show();
	            break;*/
	    }
	    return true;
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_tabs);
        
        mContext = this.getBaseContext();
        
        //<vladast>
        /*ArrayList<String> test = new ArrayList<String>();
        test.add("Majca");
        AdvancedSearchParser advParser = new AdvancedSearchParser(
        		test, 
        		"500-1000", 
        		"0", 
        		"categoryKey", 
        		"", 
        		null);
        String querystring = advParser.getAdvancedApiQueryString();
        Log.d(TAG, String.format("query: %s", querystring));*/
        //</vladast>
        
        categoryValueAdapter = ArrayAdapter.createFromResource(this, R.array.categories_key_values, android.R.layout.simple_spinner_item);

        
        // Check if the phone's connection to Internet is OK
        //TODO: Ubaciti thread!!!
        //mOffline = !BazaaroidApiClient.isOnline();
        mOffline = false;
        // TODO: show warning if phone is in offline mode
        
        // Read the default locale
        // TODO: iskoristi ovu vrednost da bi utvrdio da li je podrzana ta lokalizacija
        Locale locale = Locale.getDefault();
        
        apiClient = new BazaaroidApiClient("http://beta-bazaaroid.appspot.com");
        //ArrayList<CategoryItem> categories = apiClient.retrieveAllCategories();
        //ArrayList<LocationItem> locations = apiClient.retrieveAllLocations();
        //ArrayList<ProductItem> products = apiClient.retrieveAllProducts();
        //ArrayList<ActiveDiscountItem> discounts = apiClient.retrieveActiveDiscounts();
        
        
        // Initialize the database (for testing purposes only!)
		dbBazaaAdapter = new DbBazaaAdapter(this);
		//dbBazaaAdapter.initDatabase();
		//dbBazaaAdapter = null;
        
        ll = (LinearLayout)findViewById(R.id.bazaaroid_containing_view);
    	rl1 = (RelativeLayout)findViewById(R.id.search_header_one);
    	rl2 = (RelativeLayout)findViewById(R.id.search_header_two);  
    	rl3 = (RelativeLayout)findViewById(R.id.search_header_three);
    	//searchButton1 = (ImageButton)findViewById(R.id.search_header_button1);
    	searchButton2 = (ImageButton)rl2.findViewById(R.id.search_header_button2);
    	advancedSearchButton = (Button)rl2.findViewById(R.id.search_header_advanced_search_text);
    	iconButton = (ImageView)rl2.findViewById(R.id.search_header_icon);
        
    	// removing the search headers (relative layouts) from the containing layout
    	ll.removeView(rl1);
    	ll.removeView(rl3);
    	//ll.removeView(rl2);
    	//ll.removeView(resultButton);
		ll.removeView(mapButton);
    	

		searchBox = (EditText)rl2.findViewById(R.id.search_header_edit_box);
		searchBox.requestFocus();
		searchBox.setSingleLine();
		searchBox.setOnKeyListener(mOnKeyListenerEnter);
    	
    	
    	
    	// display the initial search header (without the search box)
        displayBazaaroidSearch(true);//(false);
        
        // set click listeners for first search button and on the icon
        //searchButton1.setOnClickListener(mOnClickListener1);
        searchButton2.setOnClickListener(mOnClickListenerSearch);
        advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
        iconButton.setOnClickListener(mOnClickListener2);
        
        
        
        // read the display settings
        Display display = getWindowManager().getDefaultDisplay(); 
        displayWidth = display.getWidth();
        displayHeight = display.getHeight();
        Log.d("[Tabs]", String.format("Display width/height = %d/%d", displayWidth, displayHeight));
        
        
        
        //resultButton = (ImageButton)findViewById(R.id.result_button);
        mapButton = (ImageButton)findViewById(R.id.map_button);
        //resultButton.setOnClickListener(mOnClickListenerResult);
        mapButton.setOnClickListener(mOnClickListenerMap);   
        ll.removeView(mapButton);
        //ll.removeView(resultButton);
        
        
        
        //TODO:
        if(mOffline)
        {
        	updateResultList("", false);
        }
        else
        {
        	//displayActiveDiscounts();
        	displayCategories();
        }
                  
        // Set MapView properties
        mMapContainer = (FrameLayout)findViewById(R.id.map_container);
        mMapResults = (MapView)mMapContainer.findViewById(R.id.mapview);
        mMapResults.setBuiltInZoomControls(true);
        
        // Result button located on the map
        resultButton = (ImageButton)mMapContainer.findViewById(R.id.result_button);
        resultButton.setOnClickListener(mOnClickListenerResult);
        
        mapController = mMapResults.getController(); 
        mapController.setZoom(14);
        
        
        
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationListener = new BazaaroidLocationListener();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
      
        
        boolean networkEnabled = false;
        try
        {
        	gpsEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        catch(Exception ex)
        {
        	Log.e(TAG, ex.getMessage());
        } 
        try
        {
        	networkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
        catch(Exception ex)
        {
        	Log.e(TAG, ex.getMessage());
        } 
 
        
        
        double latitude, longitude;
        latitude = 0;
        longitude = 0;
        
        try
        {
        	if(gpsEnabled)
        	{
	        	latitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
	        	longitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
        	}
        	else
        	{
	        	latitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude();
	        	longitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude();
        	}
        }
        catch(SecurityException se)
        {
        	Log.e(TAG, se.getMessage());
        }
        catch(IllegalArgumentException iae)
        {
        	Log.e(TAG, iae.getMessage());
        }        
        catch(Exception e)
        {
        	Log.e(TAG, e.getMessage());
        }
        
        
        
        //Get the current location in start-up
        /*
        myLatitude.setText(String.valueOf(  
        		myLocationManager.getLastKnownLocation(    
        				LocationManager.GPS_PROVIDER).getLatitude()));
        
        myLongitude.setText(String.valueOf( 
        		myLocationManager.getLastKnownLocation(   
        				LocationManager.GPS_PROVIDER).getLongitude()));
        */
        
        GeoPoint pointNbgd = new GeoPoint/*((int)(longitude * 1E6), (int)(latitude * 1E6));//*/(44805092, 20404608);
        mapController.setCenter(pointNbgd);
        
        Drawable centerImage = this.getResources().getDrawable(R.drawable.center_location_small);
        centerImage.setBounds(0, 0, centerImage.getIntrinsicWidth(), centerImage.getIntrinsicHeight());
        int imageWidth = centerImage.getIntrinsicWidth();
        int imageHeight = centerImage.getIntrinsicHeight();
        MapCenterOverlay mapOverlay = new MapCenterOverlay(centerImage, this);
        mapOverlay.setDisplayWidth(displayWidth);
        OverlayItem centerOverlay = new OverlayItem(pointNbgd, "Hello!", "My starting point");
        mapOverlay.addOverlay(centerOverlay);
        
        mMapResults.getOverlays().add(mapOverlay);
        ll.removeView(mMapContainer);//(mMapResults);
       
     
        
        /*List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.etzfvnxf);
        HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(drawable);
        
        GeoPoint point = new GeoPoint(19240000, -99120000);
        OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
        
        GeoPoint point2 = new GeoPoint(35410000, 13946000);
        OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!", "I'm in Japan!");
        
        GeoPoint point3 = new GeoPoint(44805092, 20404608);
        OverlayItem overlayitem3 = new OverlayItem(point3, "Zdravo bili!", "Ja u Beogradu!");
        
        itemizedOverlay.addOverlay(overlayitem);
        itemizedOverlay.addOverlay(overlayitem2);
        itemizedOverlay.addOverlay(overlayitem3);        
        mapOverlays.add(itemizedOverlay);*/
    }
    
    private void updateResultList(final AdvancedSearchParser advancedSearchParser)
    {
    	if(dbBazaaAdapter == null)
    	{
    		dbBazaaAdapter = new DbBazaaAdapter(this);
    	}
		mListViewResults = (ListView)findViewById(android.R.id.list);//(R.id.SearchResults);
		
		mQuery = "";//query;
		Log.d(TAG, "Received query params:\n");
		//Log.d(TAG, String.format("\tFirst query param: '%s'", advancedSearchParser.getProductNames().get(0)));
		//Log.d(TAG, String.format("\tSecond query param: '%s'", advancedSearchParser.getProductNames().get(1)));
		Log.d(TAG, String.format("\tMinimum price: %d", advancedSearchParser.getMinPrice()));
		Log.d(TAG, String.format("\tMaximum price: %d", advancedSearchParser.getMaxPrice()));
		Log.d(TAG, String.format("\tDiscount: %d", advancedSearchParser.getDiscount()));
		Log.d(TAG, String.format("\tCategory key: %s", advancedSearchParser.getCategoryKey()));
		Log.d(TAG, String.format("\tPartner key: %s", advancedSearchParser.getPartnerKey()));
		
		// TODO: build an SQL query for particular param list
		mQuery = "";//query;
		
		mSearchResult = new ArrayList<Product>();
		
		mProductsAdapter = new ProductsAdapter(this, R.layout.products_row, (ArrayList<Product>)mSearchResult);
		try
		{
			mListViewResults.setAdapter(mProductsAdapter);
			//setListAdapter(this.mProductsAdapter);
            //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
			
			
			
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
       
        viewResults = new Runnable(){
            @Override
            public void run() {
            	getAdvancedSearchResults(advancedSearchParser);
            }
        };
        Thread thread =  new Thread(null, viewResults, "ObtainAdvancedSearchResultsThread");
        thread.start();
        
        mProgressDialog = ProgressDialog.show(this, getString(R.string.search_please_wait), getString(R.string.search_retrieving), true);
        
        
        
        
        //getListView().setOnItemClickListener(listlistener);
        
        mListViewResults = (ListView)findViewById(android.R.id.list);// getListView();
        if(mListViewResults != null)
        {
	        mListViewResults.setOnItemClickListener(listlistener);
	        mListViewResults.requestFocus();
        }
    }
    
    private void displayCategories()
    {
    	ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource(this, R.array.categories, android.R.layout.simple_spinner_item);
    	ArrayAdapter<CharSequence> categoryKeyAdapter = ArrayAdapter.createFromResource(this, R.array.categories_key_values, android.R.layout.simple_spinner_item);
    	ArrayList<CategoryItem> categoryItems = new ArrayList<CategoryItem>();
    	
    	for(int i = 0; i < categoryAdapter.getCount(); ++i)
    	{
    		CategoryItem catItem = new CategoryItem();
    		catItem.setName((String) categoryAdapter.getItem(i));
    		catItem.setKey((String) categoryKeyAdapter.getItem(i));
    		categoryItems.add(catItem);
    	}
    	
    	mSearchResult = categoryItems;
    	mCategoryAdapter = new CategoryAdapter(this, R.layout.category_row, categoryItems);
    	
    	mListViewCategories = (ListView)findViewById(android.R.id.list);
    	
    	if(mListViewCategories != null)
        {
    		mListViewCategories.setAdapter(mCategoryAdapter);
    		
        	mListViewCategories.setOnItemClickListener(categorylistlistener);
        	mListViewCategories.requestFocus();
        }
    	
    	
    	/*if(mOffline)
    	{
    		
    	}
    	else
    	{*/
    		/*
    		mListViewResults = (ListView)findViewById(android.R.id.list);//(R.id.SearchResults);
    		
    		mSearchResult = new ArrayList<CategoryItem>();
    		
    		mCategoryAdapter = new CategoryAdapter(this, R.layout.category_row, (ArrayList<CategoryItem>)mSearchResult);
    		try
    		{
    			mListViewCategories.setAdapter(mCategoryAdapter);
    		}
    		catch(Exception e)
    		{
    			Log.e(TAG, e.getMessage());
    		}
           
    		viewCategories = new Runnable(){
                @Override
                public void run() {
                	getCategories();
                }
            };
            
            Log.d(TAG, "Creating 'ObtainCategoriesThread'...");
            Thread thread =  new Thread(null, viewCategories, "ObtainCategoriesThread");
            try
            {
            	Log.d(TAG, "Starting 'ObtainCategoriesThread...");
            	thread.start();
            }
            catch(Exception exc)
            {
            	Log.e(TAG, exc.getMessage());
            }
            
            mProgressDialog = ProgressDialog.show(this, getString(R.string.search_please_wait), getString(R.string.search_retrieving), true);
                        
            mListViewCategories = (ListView)findViewById(android.R.id.list);// getListView();
            if(mListViewCategories != null)
            {
            	// TODO: check if correct
            	mListViewCategories.setOnItemClickListener(categorylistlistener);
            	mListViewCategories.requestFocus();
            }*/
    	//}
    }
    
    private void displayActiveDiscounts()
    {
    	/*if(mOffline)
    	{
    		
    	}
    	else
    	{*/
    		mListViewResults = (ListView)findViewById(android.R.id.list);//(R.id.SearchResults);
    		
    		mSearchResult = new ArrayList<ActiveDiscountItem>();
    		
    		this.mActiveDiscountAdapter = new ActiveDiscountAdapter(this, R.layout.products_row, (ArrayList<ActiveDiscountItem>)mSearchResult);
    		try
    		{
    			mListViewResults.setAdapter(mActiveDiscountAdapter);
    			//setListAdapter(this.mProductsAdapter);
                //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
    			
    			
    			
    		}
    		catch(Exception e)
    		{
    			Log.e(TAG, e.getMessage());
    		}
           
            viewResults = new Runnable(){
                @Override
                public void run() {
                	getActiveDiscounts();
                }
            };
            Thread thread =  new Thread(null, viewResults, "ObtainActiveDiscountsThread");
            thread.start();
            
            mProgressDialog = ProgressDialog.show(this, getString(R.string.search_please_wait), getString(R.string.search_retrieving), true);
            
            
            
            
            //getListView().setOnItemClickListener(listlistener);
            
            mListViewResults = (ListView)findViewById(android.R.id.list);// getListView();
            if(mListViewResults != null)
            {
    	        mListViewResults.setOnItemClickListener(listlistener);
    	        mListViewResults.requestFocus();
            }    		
    	//}
    }
    
    private void updateResultList(String query, boolean advanced)
    {
    	// Hide the virtual keyboard
    	/*InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    	if(searchBox != null && imm != null)
    	{
	    	imm.hideSoftInputFromWindow(searchBox.getWindowToken(), 0); 
    	}*/
    	
    	
    	
    	if(dbBazaaAdapter == null)
    	{
    		dbBazaaAdapter = new DbBazaaAdapter(this);
    	}
		mListViewResults = (ListView)findViewById(android.R.id.list);//(R.id.SearchResults);
		// TODO: Proveri da li je ovo instanciranje propisno!
		//mListViewResults = new ListView(this);
		
		mQuery = query;
		Log.d(TAG, String.format("Received query string: '%s'", mQuery));
		
		
		mSearchResult = new ArrayList<Product>();
		
		mProductsAdapter = new ProductsAdapter(this, R.layout.products_row, (ArrayList<Product>)mSearchResult);
		try
		{
			mListViewResults.setAdapter(mProductsAdapter);
			//setListAdapter(this.mProductsAdapter);
            //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
			
			
			
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
       
        viewResults = new Runnable(){
            @Override
            public void run() {
            	getSearchResults();
            }
        };
        Thread thread =  new Thread(null, viewResults, "ObtainResultsThread");
        thread.start();
        
        mProgressDialog = ProgressDialog.show(this, getString(R.string.search_please_wait), getString(R.string.search_retrieving), true);
        
        
        
        
        //getListView().setOnItemClickListener(listlistener);
        
        mListViewResults = (ListView)findViewById(android.R.id.list);// getListView();
        if(mListViewResults != null)
        {
	        mListViewResults.setOnItemClickListener(listlistener);
	        mListViewResults.requestFocus();
        }
    }
    
    private void getActiveDiscounts()
    {
    	try
		{
			BazaaroidApiClient apiClient = new BazaaroidApiClient("http://beta-bazaaroid.appspot.com");
			
			mSearchResult = apiClient.retrieveActiveDiscounts();//doSearch(mQuery);
			
			Log.d(TAG, String.format("Find %d items.", mSearchResult.size()));
			
			for(int i = 0; i < mSearchResult.size(); ++i)
			{
				Log.d(TAG, String.format("%d: %s", i, ((ArrayList<ActiveDiscountItem>)mSearchResult).get(i).getProduct().getName()));
			}
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
		
		runOnUiThread(returnRes);
    }
    
    private void getCategories()
    {
    	Log.d(TAG, "Getting Categories...");
    	try
		{
    		if(apiClient == null)
    			apiClient = new BazaaroidApiClient("http://beta-bazaaroid.appspot.com");
			
    		Log.d(TAG, "Retrieving all Categories...");
    		
			mSearchResult = apiClient.retrieveAllCategories();
			
			if(mSearchResult == null)
				mSearchResult = new ArrayList<CategoryItem>();
			
			Log.d(TAG, String.format("Found %d categories.", mSearchResult.size()));
			
			/*for(int i = 0; i < mSearchResult.size(); ++i)
			{
				Log.d(TAG, String.format("%d: %s", i, ((ArrayList<CategoryItem>)mSearchResult).get(i).getName()));
			}*/
		}
		catch(Exception e)
		{
			//Log.e(TAG, (e == null) ? "Some unknown error occurred!" : e.getCause().getMessage());
			Log.e(TAG, "Error received while getting categories!");
		}
		runOnUiThread(returnRes);
    }
    
    private void getSearchResults()
	{
		try
		{
			Log.d(TAG, String.format("Running a query: '%s'", mQuery));
			
			
			mSearchResult = doSearch(mQuery);
			
			Log.d(TAG, String.format("Find %d items.", mSearchResult.size()));
			
			for(int i = 0; i < mSearchResult.size(); ++i)
			{
				Log.d(TAG, String.format("%d: %s", i, ((ArrayList<Product>)mSearchResult).get(i).getName()));
			}
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
		runOnUiThread(returnRes);
	}
    
    private void getAdvancedSearchResults(AdvancedSearchParser advancedSearchParser)
	{
		try
		{
			//Log.d(TAG, String.format("Running advanced query: '%s'", mAdvancedQuery));
			
			
			this.mSearchResult = doAdvancedSearch(advancedSearchParser);
			
			
			Log.d(TAG, String.format("Found %d products.", this.mSearchResult.size()));
			
			/*for(int i = 0; i < this.mSearchResult.size(); ++i)
			{
				Log.d(TAG, String.format("%d: %s", i, ((ArrayList<Product>)this.mSearchResult).get(i).getName()));
			}*/
			
			if(mProductsAdapter == null)
			{
				mProductsAdapter = 
						new ProductsAdapter(this, R.layout.products_row, 
								(ArrayList<Product>)this.mSearchResult);
					
				mListViewResults = (ListView)findViewById(android.R.id.list);// getListView();
		        if(mListViewResults != null)
		        {
			        mListViewResults.setOnItemClickListener(listlistener);
			        mListViewResults.requestFocus();
		        			
				
					try
					{
						mListViewResults.setAdapter(mProductsAdapter);
						//setListAdapter(this.mProductsAdapter);
			            //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
						
						
						
					}
					catch(Exception e)
					{
						Log.e(TAG, e.getMessage());
					}
				
		        }	
			}
		}
		catch(Exception e)
		{
			Log.e(TAG, e.getMessage());
		}
		runOnUiThread(returnRes);
	}
	
	private ArrayList<?> doSearch(String query)
	{
		ArrayList<Product> searchResult = null;
		if(mOffline)
		{
			searchResult = dbBazaaAdapter.doQueryProducts(mQuery);
		}
		else
		{
			//TODO: search using XML API
			AdvancedSearchParser basicSearchParser = new AdvancedSearchParser();
			ArrayList<String> productNames = new ArrayList<String>();
			productNames.add(query);
			basicSearchParser.setProductNames(productNames);
			ArrayList<ProductItem> searchResultItems = apiClient.retrieveProducts(basicSearchParser.getAdvancedApiQueryString()); 
			searchResult = parseProductItems(searchResultItems);
		}
		return new ArrayList<Product>(searchResult);
	}
	
	private ArrayList<Product> doAdvancedSearch(AdvancedSearchParser advancedSearchParser)
	{
		ArrayList<Product> searchResult = null;
		if(mOffline)
		{
			searchResult = dbBazaaAdapter.doAdvancedQueryProducts(advancedSearchParser);
		}
		else
		{
			//TODO: search using XML API
			/*
			- name (product name) or startsWith
			- category (category key)
			- partner (partner key)
			- location (location name)
			- priceFrom
			- priceTo
			*/
			String query = advancedSearchParser.getAdvancedApiQueryString();
			Log.d(TAG, String.format("Running query: '%s'", query));
			ArrayList<ProductItem> searchResultItems = apiClient.retrieveProducts(query);
			searchResult = parseProductItems(searchResultItems);
		}
		return new ArrayList<Product>(searchResult);
	}
	
	private ArrayList<ProductItem> doAdvancedSearch2(AdvancedSearchParser advancedSearchParser)
	{
		ArrayList<ProductItem> searchResult = null;
		if(mOffline)
		{
			// not applicable!
			//searchResult = dbBazaaAdapter.doAdvancedQueryProducts(advancedSearchParser);
		}
		else
		{
			//TODO: search using XML API
			/*
			- name (product name) or startsWith
			- category (category key)
			- partner (partner key)
			- location (location name)
			- priceFrom
			- priceTo
			*/
			String query = advancedSearchParser.getAdvancedApiQueryString();
			Log.d(TAG, String.format("Running query: '%s'", query));
			ArrayList<ProductItem> searchResultItems = apiClient.retrieveProducts(query);
			searchResult = searchResultItems;//parseProductItems(searchResultItems);
		}
		return new ArrayList<ProductItem>(searchResult);
	}
	
	private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
        	
            if(mSearchResult != null && mSearchResult.size() > 0)
            {
            	int searchCount = mSearchResult.size();
            	Log.d(TAG, String.format("Search count: %d", searchCount));
            	String className = mSearchResult.get(0).getClass().getName();
            	
            	if(className.contains("Product"))
            	{
            		/*if(mProductsAdapter == null)
            		{
            			mProductsAdapter = new ProductsAdapter(, R.layout.products_row, (ArrayList<Product>)mSearchResult);
            			try
            			{
            				mListViewResults.setAdapter(mProductsAdapter);
            				//setListAdapter(this.mProductsAdapter);
            	            //mProductAdapter.setOnItemClickListener(this.mProductsAdapter);
            				
            				
            				
            			}
            			catch(Exception e)
            			{
            				Log.e(TAG, e.getMessage());
            			}
            		}*/
            		
            		
	                mProductsAdapter.notifyDataSetChanged();
	                for(int i = 0; i < searchCount; ++i)
	                {
	                	Product product = (Product)(mSearchResult.get(i));
	                	mProductsAdapter.add(product);//(((ArrayList<Product>)mSearchResult).get(i));
	                }
	                
	                //mProgressDialog.dismiss();
	                mProductsAdapter.notifyDataSetChanged();
            	}
            	else if(className.contains("ActiveDiscountItem"))
            	//if(mActiveDiscountAdapter != null)
            	{
            		mActiveDiscountAdapter.notifyDataSetChanged();
	                for(int i = 0; i < mSearchResult.size(); ++i)
	                	mActiveDiscountAdapter.add(((ArrayList<ActiveDiscountItem>)mSearchResult).get(i));
	                
	                //mProgressDialog.dismiss();
	                mActiveDiscountAdapter.notifyDataSetChanged();
            	}
            	else if(className.contains("CategoryItem"))
            	{
            		mCategoryAdapter.notifyDataSetChanged();
	                for(int i = 0; i < mSearchResult.size(); ++i)
	                	mCategoryAdapter.add(((ArrayList<CategoryItem>)mSearchResult).get(i));
	                
	                //mProgressDialog.dismiss();
	                mCategoryAdapter.notifyDataSetChanged();
            	}
            }
            if(mProgressDialog != null)
            	mProgressDialog.dismiss();
        }
      };
      
  private OnItemClickListener listlistener = new OnItemClickListener() {

	  @Override
	  public void onItemClick(AdapterView<?> parent, View view, int position, long row_id) 
	  {
		  String className = parent.getItemAtPosition(position).getClass().getName();
		  
		  Product product = null;
		  
		  if(className.equalsIgnoreCase("com.bazaaroid.mobile.db.model.partner.Product"))
		  {
			  product = (Product)parent.getItemAtPosition(position);
			  showProductDetailsDialog(product, null, null, null);
		  }
		  else
		  {
			  ActiveDiscountItem activeDiscount = (ActiveDiscountItem)parent.getItemAtPosition(position);
			  ProductItem productItem = activeDiscount.getProduct();
			  //product = parseProductItem(productItem);
			  showProductDetailsDialog(productItem);
		  }
		  
		  
	  }
  };
    
  private OnItemClickListener categorylistlistener = new OnItemClickListener() {

	  @Override
	  public void onItemClick(AdapterView<?> parent, View view, int position, long row_id) 
	  {
		  // Switch search header
		  if(rl2.isShown())
			{
				ll.removeView(rl2);
			  	ll.addView(rl3, 0);
			}
		  /*ll.removeView(rl2);
		  ll.addView(rl3, 0);*/
		  searchButton2 = (ImageButton)rl3.findViewById(R.id.search_header_button2);
		  advancedSearchButton = (Button)rl3.findViewById(R.id.search_header_advanced_search_text);
		  iconButton = (ImageView)rl3.findViewById(R.id.search_header_icon);		  
		  
		  searchBox = (EditText)rl3.findViewById(R.id.search_header_edit_box);
		  searchBox.requestFocus();
		  searchBox.setSingleLine();
		  searchBox.setOnKeyListener(mOnKeyListenerEnter);

		  searchButton2.setOnClickListener(mOnClickListenerSearch);
		  advancedSearchButton.setOnClickListener(mOnClickListenerAdvancedSearch);
		  iconButton.setOnClickListener(mOnClickListener2);		  
		  
		  String className = parent.getItemAtPosition(position).getClass().getName();
		  
		  Product product = null;
		  
		  if(className.contains("Product"))
		  {
			  product = (Product)parent.getItemAtPosition(position);
			  showProductDetailsDialog(product, null, null, null);
		  }
		  else if(className.contains("ActiveDiscountItem"))
		  {
			  ActiveDiscountItem activeDiscount = (ActiveDiscountItem)parent.getItemAtPosition(position);
			  ProductItem productItem = activeDiscount.getProduct();
			  //product = parseProductItem(productItem);
			  showProductDetailsDialog(productItem);
		  }
		  else if(className.contains("CategoryItem"))
		  {
			  CategoryItem category = (CategoryItem)parent.getItemAtPosition(position);
			  /*ProductItem productItem = activeDiscount.getProduct();
			  //product = parseProductItem(productItem);
			  showProductDetailsDialog(productItem);*/
			  AdvancedSearchParser advSrchParser = new AdvancedSearchParser();//(new ArrayList<String>(), "", 0, category.getKey(), "", "");
			  advSrchParser.setCategoryKey(category.getKey());
			  //getAdvancedSearchResults(advSrchParser);
			  updateResultList(advSrchParser);
		  }
		  else if(className.contains("String"))
		  {
			  String categoryKey = (String) categoryValueAdapter.getItem(position);
			  AdvancedSearchParser advSrchParser = new AdvancedSearchParser();//(new ArrayList<String>(), "", 0, category.getKey(), "", "");
			  advSrchParser.setCategoryKey(categoryKey);
			  getAdvancedSearchResults(advSrchParser);
		  }
		  
		  
	  }
  };
  
  	private ArrayList<Product> parseProductItems(ArrayList<ProductItem> productItems)
  	{
  		ArrayList<Product> products = new ArrayList<Product>();
  		
  		for(int i = 0; i < productItems.size(); ++i)
  		{
  			Product product = parseProductItem(productItems.get(i));
  			products.add(product);
  		}
  		
  		return products;
  	}
  
  	private Product parseProductItem(ProductItem productItem)
  	{
  		PartnerItem partnerItem = productItem.getPartner();
		ContactItem contactItem = partnerItem.getContact();
		  
		Contact contact = new Contact();
		contact.setEmail(contactItem.getEmail());
		contact.setFax(contactItem.getFax());
		contact.setMobile(contactItem.getMobile());
		contact.setSite(contactItem.getSite());
		contact.setTelephone(contactItem.getTelephone());
		  
		Partner partner = new Partner();
		partner.setKey(Integer.valueOf(partnerItem.getKey()));
		partner.setName(partnerItem.getName());
		partner.setDescription(partnerItem.getDescription());
		partner.setContact(contact);
		  
		Product product = new Product(); 
		product.setName(productItem.getName());
		product.setDescription(productItem.getDescription());
		product.setPrice(Double.parseDouble(productItem.getPrice()));
		  //product.setDiscount(Integer.parseInt(productItem.getDiscount().getPercentage()));
		product.setCurrency(productItem.getCurrency());
		product.setKey(Integer.valueOf(productItem.getKey()));
		product.setPartner(partner);
		
		ArrayList<LocationItem> locationItems = productItem.getLocations();
		Set<Location> locations = new HashSet<Location>();
		for(int i = 0; i < locationItems.size(); ++i)
		{
			locations.add(parseLocationItem(locationItems.get(i)));
		}
		product.setLocations(locations);
		
		return product;
  	}
  
  	private Location parseLocationItem(LocationItem locationItem)
  	{
  		Location location = new Location();	
  		location.setKey(Integer.valueOf(locationItem.getKey()));
  		location.setName(locationItem.getName());
  		location.setOpeningHours(locationItem.getOpeningHours());
  		
  		GeoPt geoPoint = new GeoPt();
  		geoPoint.setLatitude((int) (locationItem.getGeoPt().getLatitude() * 1E6));
  		geoPoint.setLongitude((int) (locationItem.getGeoPt().getLongitude() * 1E6));
  		location.setGeoPoint(geoPoint);
  		
  		return location;
  	}
  	
    private void displayBazaaroidSearch(boolean show)
    {
    	/*
    	if(show)
    	{
    		ll.removeView(rl1);
    		ll.addView(rl2, 0);
    	}
    	else
    	{
    		ll.addView(rl1, 0);
    		ll.removeView(rl2);
    	}*/
    }
    
    private void displayResult(boolean show)
    {
    	if(mMapContainer == null)
    		mMapContainer = (FrameLayout)findViewById(R.id.map_container);
    	if(mMapResults == null)
    		mMapResults = (MapView)mMapContainer.findViewById(R.id.mapview);
    	if(mListViewResults == null)
    		mListViewResults = (ListView)findViewById(android.R.id.list);
    	
    	
    	ll.removeView(mMapContainer);//(mMapResults);
    	ll.removeView(mListViewResults);
    	if(mListViewCategories != null)
    		ll.removeView(mListViewCategories);
    	
    	if(show)
    	{
    		// remove Map, add Result
    		//ll.removeView(mMapResults);
    		ll.addView(mListViewResults, 1);
    	}
    	else
    	{
    		// remove Result, add Map
    		//ll.addView(mMapResults, 1);
    		ll.addView(mMapContainer, 1);
    		//ll.removeView(mListViewResults);
    	}
    }
    
    private void showProductDetailsDialog(ProductItem productItem)
    {
    	final Dialog dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.list_item_details);
    	//dialog.setTitle(getString(R.string.selected_item_title));
    	dialog.setCancelable(true);
    	
        //int displayHeight = display.getHeight();

    	ImageView productImage = null;
    	TextView productName = null;
    	TextView productDescription = null;
    	TextView productPrice = null;
    	TextView productCurrency = null;
    	Button backButton = null;
    	Button mapButton = null;
    	LinearLayout listItemDetails = null;
    	LinearLayout productHolder = null;
    	LinearLayout productDetails = null;
    	LinearLayout nameAndDescription = null;
    	LinearLayout priceAndCurrency = null;
    	LinearLayout buttonHolder = null;
    	
    	
    	/*ImageView categoryImage = null;
    	TextView productName = null;
    	TextView productDescription = null;
    	TextView productPartner = null;
    	TextView productLocation = null;
    	TextView productDiscount = null;
    	Button okButton = null;

    	LinearLayout nameAndCategory = null;*/
    	
    	listItemDetails = (LinearLayout)dialog.findViewById(R.id.list_item_details);
    	listItemDetails.setMinimumWidth((int)(displayWidth));
    	//listItemDetails.setMinimumHeight((int)(displayWidth * 0.8));
    	
    	productHolder = (LinearLayout)dialog.findViewById(R.id.selected_item_product);
    	
    	productDetails = (LinearLayout)productHolder.getChildAt(1);
    	
    	
    	productImage = (ImageView)productHolder.getChildAt(0);//(ImageView)dialog.findViewById(R.id.selected_item_image);
    	
    	productName = (TextView)productDetails.getChildAt(0);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productName.setText(productItem.getName());
    	
    	productDescription = (TextView)productDetails.getChildAt(1);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productDescription.setText(productItem.getDescription());
    	
    	priceAndCurrency = (LinearLayout)productDetails.getChildAt(2);
    	
    	productPrice = (TextView)priceAndCurrency.getChildAt(0);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productPrice.setText(productItem.getPrice());
    	
    	productCurrency = (TextView)priceAndCurrency.getChildAt(1);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productCurrency.setText(productItem.getCurrency());
    	
    	buttonHolder = (LinearLayout)listItemDetails.getChildAt(1);
    	
    	backButton = (Button)buttonHolder.getChildAt(0);//(Button)dialog.findViewById(R.id.selected_item_back_button);
    	backButton.setWidth(displayWidth / 2);
    	backButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			//finish();
    			dialog.dismiss();
    		}
    	});
    	
    	mapButton = (Button)buttonHolder.getChildAt(1);//(Button)dialog.findViewById(R.id.selected_item_map_button);
    	mapButton.setWidth(displayWidth / 2);
    	mapButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			// TODO: prikazati lokaciju na mapi!!!
    			dialog.dismiss();
    		}
    	});
    	
    	
    	/*nameAndCategory = (LinearLayout)dialog.findViewById(R.id.name_and_category);
    	
    	categoryImage = (ImageView)nameAndCategory.getChildAt(0);// (ImageView)findViewById(R.id.category_image);
    	// TODO: Set the category image!
    	categoryImage.setImageResource(R.drawable.icon);
    	
    	productName = (TextView)nameAndCategory.getChildAt(1);//(TextView)findViewById(R.id.product_name);
    	productName.setText(productItem.getName());
    	
    	productDescription = (TextView)dialog.findViewById(R.id.product_description);
    	productDescription.setText(productItem.getDescription());
    	
    	if(productItem.getPartner() != null)
    	{
	    	productPartner = (TextView)dialog.findViewById(R.id.product_partner);
	    	productPartner.setText(getString(R.string.item_partner_prefix) + productItem.getPartner().getName());
    	}*/
    	
    	/*if(productItem.getLocations() != null)
    	{
	    	productLocation = (TextView)dialog.findViewById(R.id.product_location);
	    	productLocation.setText(getString(R.string.item_location_prefix) + location.getName());
    	}*/
    	
    	/*if(productItem.getDiscount() != null)
    	{
	    	productDiscount = (TextView)dialog.findViewById(R.id.product_discount);
	    	productDiscount.setText(getString(R.string.item_discount_prefix) + productItem.getDiscount().getPercentage() + "%%");
    	}
    	
    	okButton = (Button)dialog.findViewById(R.id.ok_button);
    	okButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			//finish();
    			dialog.dismiss();
    		}
    	});*/
    	
    	dialog.show();
    }
    
    private void showProductDetailsDialog(final Product product, Partner partner, Location location, Discount discount)
    {
    	final Dialog dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.list_item_details);
    	//dialog.setTitle(getString(R.string.selected_item_title));
    	dialog.setCancelable(true);
    	
    	ImageView productImage = null;
    	TextView productName = null;
    	TextView productDescription = null;
    	TextView productPrice = null;
    	TextView productCurrency = null;
    	Button backButton = null;
    	Button mapButton = null;
    	LinearLayout listItemDetails = null;
    	LinearLayout productHolder = null;
    	LinearLayout productDetails = null;
    	LinearLayout nameAndDescription = null;
    	LinearLayout priceAndCurrency = null;
    	LinearLayout buttonHolder = null;
    	
    	
    	/*ImageView categoryImage = null;
    	TextView productName = null;
    	TextView productDescription = null;
    	TextView productPartner = null;
    	TextView productLocation = null;
    	TextView productDiscount = null;
    	Button okButton = null;

    	LinearLayout nameAndCategory = null;*/
    	
    	listItemDetails = (LinearLayout)dialog.findViewById(R.id.list_item_details);
    	listItemDetails.setMinimumWidth((int)(displayWidth));
    	//listItemDetails.setMinimumHeight((int)(displayWidth * 0.8));
    	
    	productHolder = (LinearLayout)dialog.findViewById(R.id.selected_item_product);
    	
    	productDetails = (LinearLayout)productHolder.getChildAt(1);
    	
    	
    	productImage = (ImageView)productHolder.getChildAt(0);//(ImageView)dialog.findViewById(R.id.selected_item_image);
    	
    	productName = (TextView)productDetails.getChildAt(0);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productName.setText(product.getName());
    	
    	productDescription = (TextView)productDetails.getChildAt(1);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productDescription.setText(product.getDescription());
    	
    	priceAndCurrency = (LinearLayout)productDetails.getChildAt(2);
    	
    	productPrice = (TextView)priceAndCurrency.getChildAt(0);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productPrice.setText(String.valueOf((int)product.getPrice()));
    	
    	productCurrency = (TextView)priceAndCurrency.getChildAt(1);//(TextView)dialog.findViewById(R.id.selected_item_name);
    	productCurrency.setText(product.getCurrency());
    	
    	buttonHolder = (LinearLayout)listItemDetails.getChildAt(1);
    	
    	backButton = (Button)buttonHolder.getChildAt(0);//(Button)dialog.findViewById(R.id.selected_item_back_button);
    	backButton.setWidth(displayWidth / 2);
    	backButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			//finish();
    			dialog.dismiss();
    		}
    	});
    	
    	mapButton = (Button)buttonHolder.getChildAt(1);//(Button)dialog.findViewById(R.id.selected_item_map_button);
    	mapButton.setWidth(displayWidth / 2);
    	mapButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			// TODO: prikazati lokaciju na mapi!!!
    			showLocations(product);
    			dialog.dismiss();
    		}
    	});
    	
    	
        //int displayHeight = display.getHeight();

 /*   	ImageView categoryImage = null;
    	TextView productName = null;
    	TextView productDescription = null;
    	TextView productPartner = null;
    	TextView productLocation = null;
    	TextView productDiscount = null;
    	Button okButton = null;
    	LinearLayout listItemDetails = null;
    	LinearLayout nameAndCategory = null;
    	
    	listItemDetails = (LinearLayout)dialog.findViewById(R.id.list_item_details);
    	listItemDetails.setMinimumWidth((int)(displayWidth * 0.8));
    	//listItemDetails.setMinimumHeight((int)(displayWidth * 0.8));
    	
    	nameAndCategory = (LinearLayout)dialog.findViewById(R.id.name_and_category);
    	
    	categoryImage = (ImageView)nameAndCategory.getChildAt(0);// (ImageView)findViewById(R.id.category_image);
    	// TODO: Set the category image!
    	categoryImage.setImageResource(R.drawable.icon);
    	
    	productName = (TextView)nameAndCategory.getChildAt(1);//(TextView)findViewById(R.id.product_name);
    	productName.setText(product.getName());
    	
    	productDescription = (TextView)dialog.findViewById(R.id.product_description);
    	productDescription.setText(product.getDescription());
    	
    	if(partner != null)
    	{
	    	productPartner = (TextView)dialog.findViewById(R.id.product_partner);
	    	productPartner.setText(getString(R.string.item_partner_prefix) + partner.getName());
    	}
    	
    	if(location != null)
    	{
	    	productLocation = (TextView)dialog.findViewById(R.id.product_location);
	    	productLocation.setText(getString(R.string.item_location_prefix) + location.getName());
    	}
    	
    	if(discount != null)
    	{
	    	productDiscount = (TextView)dialog.findViewById(R.id.product_discount);
	    	productDiscount.setText(getString(R.string.item_discount_prefix) + String.valueOf(discount.getPercentage()));
    	}
    	
    	okButton = (Button)dialog.findViewById(R.id.ok_button);
    	okButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			//finish();
    			dialog.dismiss();
    		}
    	});*/
    	
    	dialog.show();
    }
    
    private void displayAdvancedSearchDialog()
    {
    	final Dialog dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.advanced_search);
    	dialog.setCancelable(true);
    	
    	final String query = "";
    	
    	LinearLayout advancedSearchLayout = (LinearLayout)dialog.findViewById(R.id.advanced_search_dialog);
    	advancedSearchLayout.setMinimumWidth(displayWidth);
    	int advLayoutWidth = advancedSearchLayout.getWidth();
    	
    	/*
    	<string name="advanced_search_find_products">Find products with name like:</string>
    	<string name="advanced_search_or_text">OR</string>
    	<string name="advanced_search_price_range">Select price range:</string>
    	<string name="advanced_search_discount">Select discount:</string>
    	<string name="advanced_search_category">Select category:</string>
    	<string name="advanced_search_partner">Select seller:</string>
    	<string name="advanced_search_distance">Enter distance radius:</string>
    	*/
    	
    	final EditText findProductsEdit = (EditText)dialog.findViewById(R.id.advanced_search_product_edit);
    	//final EditText orProductEdit = (EditText)dialog.findViewById(R.id.advanced_search_or_edit);
    	
    	final Spinner priceSpinner = (Spinner)dialog.findViewById(R.id.advanced_search_price_range_spinner);
    	final ArrayAdapter<CharSequence> priceAdapter = ArrayAdapter.createFromResource(this, R.array.price_ranges, android.R.layout.simple_spinner_item);
    	priceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	priceSpinner.setAdapter(priceAdapter);
    	
    	
    	
    	final Spinner discountSpinner = (Spinner)dialog.findViewById(R.id.advanced_search_discount_spinner);
    	ArrayAdapter<CharSequence> discountAdapter = ArrayAdapter.createFromResource(this, R.array.discounts, android.R.layout.simple_spinner_item);
    	discountAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	discountSpinner.setAdapter(discountAdapter);
    	
    	final Spinner categorySpinner = (Spinner)dialog.findViewById(R.id.advanced_search_category_spinner);
    	ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource(this, R.array.categories, android.R.layout.simple_spinner_item);
    	// TODO: categoryValueAdapter is just a workaround - the proper way is to create adapter with set of values
    	final ArrayAdapter<CharSequence> categoryValueAdapter = ArrayAdapter.createFromResource(this, R.array.categories_key_values, android.R.layout.simple_spinner_item);
    	categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	categorySpinner.setAdapter(categoryAdapter);
    	
    	final Spinner partnerSpinner = (Spinner)dialog.findViewById(R.id.advanced_search_partner_spinner);
    	//za slucaj da se izcitava iz baze:
    	//ArrayAdapter<CharSequence> partnerAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
    	ArrayAdapter<CharSequence> partnerAdapter = ArrayAdapter.createFromResource(this, R.array.partners, android.R.layout.simple_spinner_item);
    	// TODO: see comments about categoryValueAdapter
    	final ArrayAdapter<CharSequence> partnerValueAdapter = ArrayAdapter.createFromResource(this, R.array.partners_int_values, android.R.layout.simple_spinner_item);
    	partnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	// TODO: ovo treba da se izcitava iz baze
    	
    	if(dbBazaaAdapter == null) // just in case...
    		dbBazaaAdapter = new DbBazaaAdapter(this);
    	
    	ArrayList<Partner> partners = dbBazaaAdapter.doQueryPartners("");
    	
    	/*
    	 * za slucaj da se lista partnera izcitava iz baze... kako bi i trebalo da bude...
    	partnerAdapter.add(this.getString(R.string.advanced_search_default_partner_selection));
    	
    	for(int i = 0; i < partners.size(); ++i)
    	{
    		partnerAdapter.add(partners.get(i).getName());
    	}
    	*/
    	
    	/*partnerAdapter.add("Zira");
    	partnerAdapter.add("Zara");
    	partnerAdapter.add("Tempo");
    	partnerAdapter.add("Merkator");
    	partnerAdapter.add("Uradi Sam");*/
    	partnerSpinner.setAdapter(partnerAdapter);
    	
    	// TODO: Implement distance calculation!
    	//EditText distanceRadiusEdit = (EditText)dialog.findViewById(R.id.advanced_search_distance_edit);
    	
    	// ---- bottom buttons ---- //
    	Button okButton = null;
    	Button cancelButton = null;
    	okButton = (Button)dialog.findViewById(R.id.advanced_search_ok_button);
    	okButton.setWidth(displayWidth / 2); 
    	okButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			// TODO: start search thread
    			
    			ArrayList<String> productNames = new ArrayList<String>(); // only two names possible
    			/*productNames.set(1, findProductsEdit.toString());
    			productNames.set(2, orProductEdit.toString());*/
    			productNames.add(findProductsEdit.getText().toString());
    			//productNames.add(orProductEdit.getText().toString());
    			
    			AdvancedSearchParser advancedSearchParser = new AdvancedSearchParser(
    					productNames, 
    					priceSpinner.getSelectedItem().toString(), 
    					discountSpinner.getSelectedItem().toString(), 
    					categoryValueAdapter.getItem(categorySpinner.getSelectedItemPosition()).toString(), 
    					partnerValueAdapter.getItem(partnerSpinner.getSelectedItemPosition()).toString(),
    					"" // locationName
    			);
    			
    			
    			updateResultList(advancedSearchParser);
    			dialog.dismiss();
    		}
    	});
    	
    	cancelButton = (Button)dialog.findViewById(R.id.advanced_search_cancel_button);
    	cancelButton.setWidth(displayWidth / 2);
    	cancelButton.setOnClickListener(new OnClickListener(){
    		@Override
    		public void onClick(View v){
    			dialog.dismiss();
    		}
    	});
    	
    	dialog.show();
    }
    
    void showLocations(Product product)
    {
    	Set<Location> locations = product.getLocations();
    	
    	ll.removeView(mListViewResults);
    	mMapResults.getOverlays().clear();
    	
    	addCenterMapLayer();
    	
    	// TODO: Show locations on the map
    	//ArrayList<Location> foundLocations = new ArrayList<Location>();
    	Location[] locArray = new Location[locations.size()];
    	locations.toArray(locArray);
    	
    	
    	
    	for(int i = 0; i < locations.size(); ++i)
    	{
    		// TODO: Dodati novi layer na mapi za svaku od lokacija.
    		Log.d(TAG, locArray[i].getName());
    		addProductMapLayer(product, locArray[i]);
    	}
    	
    	//mMapResults.invalidate();
    	
    	//ll.addView(resultButton);
    	
    	//ll.addView(mMapResults);
    	ll.addView(mMapContainer);
    }
    
    void addCenterMapLayer()
    {
    	double latitude, longitude;
        latitude = 0;
        longitude = 0;
        
        try
        {
        	if(gpsEnabled)
        	{
	        	latitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
	        	longitude = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
        	}
        	else
        	{
	        	latitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude();
	        	longitude = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude();
        	}
        	
        	//Log.d(TAG, String.format("latitude: %d, longitude: %d", latitude, longitude));
        	GeoPoint pointNbgd = new GeoPoint((int)(latitude * 1E6), (int)(longitude * 1E6));
            mapController.setCenter(pointNbgd);
            
            Drawable centerImage = this.getResources().getDrawable(R.drawable.center_location_small);
            centerImage.setBounds(0, 0, centerImage.getIntrinsicWidth(), centerImage.getIntrinsicHeight());
            MapCenterOverlay mapOverlay = new MapCenterOverlay(centerImage, this);
            mapOverlay.setDisplayWidth(displayWidth);
            OverlayItem centerOverlay = new OverlayItem(pointNbgd, "new", "location"); // dummy strings...
            mapOverlay.addOverlay(centerOverlay);
            
            
            //if(mMapResults.getOverlays().size() > 0)
            //{
            //	((MapCenterOverlay)mMapResults.getOverlays().get(0)).addOverlay(centerOverlay);
            //}
            //else
            //{
                mMapResults.getOverlays().add(mapOverlay); 
            //}
            //mMapResults.postInvalidate();
        }
        catch(SecurityException se)
        {
        	Log.e(TAG, se.getMessage());
        }
        catch(IllegalArgumentException iae)
        {
        	Log.e(TAG, iae.getMessage());
        }        
        catch(Exception e)
        {
        	Log.e(TAG, e.getMessage());
        }    	
    }
    
    void addProductMapLayer(Product product, Location location)
    {
    	Log.d(TAG, String.format("latitude: %d, longitude: %d", (int)location.getLatitude(), (int)location.getLongitude()));
    	
    	GeoPoint pointNbgd = new GeoPoint((int)location.getLatitude(), (int)location.getLongitude());
        //mapController.setCenter(pointNbgd);
        
        Drawable centerImage = this.getResources().getDrawable(R.drawable.location_1);
        centerImage.setBounds(0, 0, centerImage.getIntrinsicWidth(), centerImage.getIntrinsicHeight());
        MapProductOverlay mapOverlay = new MapProductOverlay(centerImage, this);
        mapOverlay.setDisplayWidth(displayWidth);
        mapOverlay.setProduct(product);
        
        OverlayItem centerOverlay = new OverlayItem(pointNbgd, "new", "location"); // dummy strings...
        mapOverlay.addOverlay(centerOverlay);
        
        //if(mMapResults.getOverlays().size() > 0)
        //{
        //	((MapProductOverlay)mMapResults.getOverlays().get(0)).addOverlay(centerOverlay);
        //}
        //else
        //{
            mMapResults.getOverlays().add(mapOverlay); 
        //}
        //mMapResults.postInvalidate();
    }
}